package com.hongye.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.hongye.app.model.BuyerAddressModel;
import com.hongye.app.model.BuyerStatisticsModel;
import com.hongye.app.model.EvaluationModel;
import com.hongye.app.model.ExpressModel;
import com.hongye.app.model.GoodsModel;
import com.hongye.app.model.OrderGoodsModel;
import com.hongye.app.model.OrderInfoModel;
import com.hongye.app.model.OrderTracesModel;
import com.hongye.app.model.PaymentModel;
import com.hongye.app.model.ReturnGoodsModel;
import com.hongye.app.model.ShoppingCartModel;
import com.hongye.app.model.UserAppModel;
import com.hongye.util.AlipayUtils;
import com.hongye.util.JsonUtils;
import com.hongye.util.KDNiaoUtils;
import com.hongye.util.PushUtils;
import com.hongye.util.Utils;
import com.hongye.util.WeixinUtils;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

/**
 * app订单相关
 * @author Administrator
 *
 */
public class AppOrderController extends Controller{
	
	private Logger log = Logger.getLogger(getClass());
	public static String ImgPath = "http://120.27.117.192/rbg/upload/";//服务器图片路径
	public static String Status = "6,7,9,11";//已完成的订单
	public AppOrderController() {
		
	}
	
	/**
	 * 参数接收——String
	 * this.getParam
	 * @author lifuqiang
	 * 2016-10-31
	 * @param param
	 * @return
	 */
	public String getPa(String param) {
		return this.getPara(param);
	}
	
	/**
	 * 参数接收——int
	 * this.getParaToInt
	 * @author lifuqiang
	 * 2016-11-14
	 * @return
	 */
	@Clear
	public int getParaInt(String param){
		return this.getParaToInt(param);
	}
	
	/**
	 * 参数接收——UploadFile
	 * this.getFile
	 * @author lifuqiang
	 * 2017-2-4
	 * @return
	 */
	public UploadFile getfile(String fileName){
		int maxPostSize = 20 * 1024 * 1024;
		return this.getFile(fileName, "", maxPostSize);
	}
	
	/**
	 * 订单列表  买家待付款订单列表
	 * @author liushaomin
	 * 2017年7月14日
	 */
	@Clear
	public void buyerOrderNoPay(){
		String phone = getPa("phone");
		String state = getPa("state");
		Map<String, Object> rs = new HashMap<String, Object>();
		List<OrderInfoModel> orderlist = OrderInfoModel.getNoPayOrder(phone, state);
		rs.put("orderlist", orderlist);
		this.renderJson(rs);
	}
	
	/**
	 * 买家订单列表--已分页处理
	 * 状态state（2,8：待发货；3,10：待收货；5：待评价；all:全部）
	 * @author liushaomin
	 * 2017年7月14日
	 */
	@Clear
	public void buyerOrder(){
		String phone = getPa("phone");
		String state = getPa("state");
		int pageNumber = getParaInt("pageNumber");
		if(state.equals("all")){
			state = Status;
		}
		Map<String, Object> rs = new HashMap<String, Object>();
		Page<OrderInfoModel> page_orderlist = OrderInfoModel.getOrderListByStatus(phone, state, pageNumber);
		rs.put("orderlist", page_orderlist);
		this.renderJson(rs);
	}
	
	/**
	 * 卖家获取订单列表--已添加分页
	 * 状态state（0,2：待发货；3：待收货；5,7,9,11,12：待评价；all:全部）
	 * @author lifuqiang
	 * 2017-3-23
	 */
	@Clear
	public void sellerOrder(){
		String state = getPa("state");
		String phone = getPa("phone");
		int pageNumber = getParaInt("pageNumber");
		if(state.equals("all")){
			state = Status;
		}
		Page<OrderInfoModel> page_orderlist = OrderInfoModel.getOrderlistBySeller(phone, state, pageNumber);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("orderlist", page_orderlist);
		this.renderJson(rs);
	}
	
	
	/**
	 * 买家查询退货列表---已添加分页
	 * @param 买家电话
	 * @param pageNumber
	 * @author lifuqiang
	 * 2017-3-23
	 */
	@Clear
	public void returnGoodsByBuyer(){
		String phone = getPa("phone");
		int pageNumber = getParaInt("pageNumber");
		Page<ReturnGoodsModel> returngoods = ReturnGoodsModel.dao.returnGoodsBybuyerPhone(phone,pageNumber);
		List<OrderInfoModel> orderlist = new ArrayList<OrderInfoModel>();
		for(ReturnGoodsModel r_goods : returngoods.getList()){
			OrderInfoModel info = OrderInfoModel.getOrder_byOrdersn_Buyer(r_goods.getStr("g_order"));
			info.put("isreturn_goods", r_goods.get("isreturn_goods"));
			info.put("return_id", r_goods.get("return_id"));
			info.put("return_status", r_goods.get("return_status"));
			orderlist.add(info);
		}
		Map<String, Object> ordermap = new HashMap<String, Object>();
		ordermap.put("list", orderlist);
		ordermap.put("totalRow", returngoods.getTotalRow());
		ordermap.put("pageNumber", returngoods.getPageNumber());
		ordermap.put("lastPage", returngoods.getTotalPage());
		ordermap.put("firstPage", returngoods.isFirstPage());
		ordermap.put("lastPage", returngoods.isLastPage());
		ordermap.put("pageSize", returngoods.getPageSize());
		ordermap.put("totalPage", returngoods.getTotalPage());
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("returngoods", ordermap);
		this.renderJson(rs);
	}
	
	
	/**
	 * 卖家查询退货列表--已添加分页
	 * @param 卖家电话
	 * @author lifuqiang
	 * 2016-10-31
	 */
	@Clear
	public void returnGoodsBySeller(){
		String phone = getPa("phone");
		int pageNumber = getParaInt("pageNumber");
		Page<ReturnGoodsModel> returngoods = ReturnGoodsModel.dao.returnGoodsBySellerPhone(phone, pageNumber);
		List<OrderInfoModel> orderlist = new ArrayList<OrderInfoModel>();
		for(ReturnGoodsModel regoods : returngoods.getList()){
			OrderInfoModel info = OrderInfoModel.getOrder_byOrdersn_Seller(regoods.getStr("g_order"));
			String sql_ordergoods = "select goods_id, goods_name, goods_price, goods_num, goods_thumb, seller_id from order_goods where order_id = "+ info.get("id") +"";
			List<OrderGoodsModel> order_goodslist =  OrderGoodsModel.dao.find(sql_ordergoods);
			for (OrderGoodsModel ordergoods_item : order_goodslist) {
				ordergoods_item.put("goods_thumb", UserAppInfoController.ImgPath + ordergoods_item.getStr("goods_thumb"));
			}
			info.put("isreturn_goods", regoods.get("isreturn_goods"));
			info.put("return_id", regoods.get("return_id"));
			info.put("return_status", regoods.get("return_status"));
			info.put("order_goodslist", order_goodslist);
			orderlist.add(info);
		}
		Map<String, Object> ordermap = new HashMap<String, Object>();
		ordermap.put("list", orderlist);
		ordermap.put("totalRow", returngoods.getTotalRow());
		ordermap.put("pageNumber", returngoods.getPageNumber());
		ordermap.put("lastPage", returngoods.getTotalPage());
		ordermap.put("firstPage", returngoods.isFirstPage());
		ordermap.put("lastPage", returngoods.isLastPage());
		ordermap.put("pageSize", returngoods.getPageSize());
		ordermap.put("totalPage", returngoods.getTotalPage());
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("returngoods", ordermap);
		this.renderJson(rs);
	}
	
	/**
	 * 买家查看订单商品详情
	 * @author liushaomin
	 * 2017年7月14日
	 */
	@Clear
	public void buyerOrderDetail(){
		String order_sn = this.getPa("order_sn");
		OrderInfoModel info = OrderInfoModel.getOrderBySN(order_sn);
		String sql_ordergoods = "select goods_id, goods_name, goods_price, goods_num, goods_thumb, seller_id from order_goods where order_id = "+ info.get("id") +"";
		List<OrderGoodsModel> ordergoodslist = OrderGoodsModel.dao.find(sql_ordergoods);
		for (OrderGoodsModel ordergoods_item : ordergoodslist) {
			ordergoods_item.put("goods_thumb", UserAppInfoController.ImgPath + ordergoods_item.getStr("goods_thumb"));
		}
		BuyerStatisticsModel seller_shop = BuyerStatisticsModel.getStatisticsByID(ordergoodslist.get(0).get("seller_id").toString());
		List<Map<String, Object>> list_traces = new ArrayList<Map<String,Object>>();
		Map<String, Object> rs = new HashMap<String, Object>();
		info.put("ordergoodslist", ordergoodslist);
		info.put("seller_phone", seller_shop.get("buyer_phone"));
		info.put("shop_name", seller_shop.get("shop_name"));
		info.put("shop_avatar", ImgPath + BuyerStatisticsModel.getShop_avatarByPhone(seller_shop.getStr("buyer_phone")));
		info.put("Traces", null);
		if(info.getStr("waybillnumber")!=null){
			list_traces.add(OrderTracesModel.getNewTraces(info.getStr("waybillnumber")));//平台推送查询
			info.put("Traces", list_traces);
		}
		info.put("return_id", null);
		ReturnGoodsModel rg = ReturnGoodsModel.getByG_order(info.getStr("order_sn"), 1);
		if(rg != null){
			info.put("return_id", rg.get("return_id"));
		}
		info.remove("user_id");
		info.remove("del");
		info.remove("orderids");
		info.remove("trade_num");
		info.remove("update_time");
		info.remove("phone");
		info.remove("type");
		info.remove("settlement_time");
		info.remove("country");
		info.remove("zipcode");
		info.remove("pay_time");
		info.remove("payment_channel");
		rs.put("orderdetail", info);
		this.renderJson(rs);
	}
	
	/**
	 * 买家查看退款详情
	 * @author lifuqiang
	 * 2017-4-13
	 */
	@Clear
	public void buyerReturnGoodsDetail(){
		String order_sn = this.getPa("order_sn");
		ReturnGoodsModel returngoods = ReturnGoodsModel.getReturnGoodsByorder(order_sn);
		Map<String, Object> map = new HashMap<String, Object>();
		returngoods.put("nick", UserAppModel.getById(returngoods.get("seller_id").toString()).get("nick"));
		returngoods.remove("seller_id");
		map.put("returngoods", returngoods);
		this.renderJson(map);
	}
	
	/**
	 * 卖家查看订单商品详情
	 * @author liushaomin
	 * 2017年7月14日
	 */
	@Clear
	public void sellerOrderDetail(){
		String order_sn = this.getPa("order_sn");
		OrderInfoModel info = OrderInfoModel.getOrderBySN(order_sn);
		String sql_ordergoods = "select goods_id, goods_name, goods_price, goods_num, goods_thumb, seller_id from order_goods where order_id = "+ info.get("id") +"";
		List<OrderGoodsModel> ordergoodslist = OrderGoodsModel.dao.find(sql_ordergoods);
		for (OrderGoodsModel ordergoods_item : ordergoodslist) {
			ordergoods_item.put("goods_thumb", UserAppInfoController.ImgPath + ordergoods_item.getStr("goods_thumb"));
		}
		BuyerStatisticsModel seller_shop = BuyerStatisticsModel.getStatisticsByID(ordergoodslist.get(0).get("seller_id").toString());
		List<Map<String, Object>> list_traces = new ArrayList<Map<String,Object>>();
		Map<String, Object> rs = new HashMap<String, Object>();
		info.put("ordergoodslist", ordergoodslist);
		info.put("seller_phone", seller_shop.get("buyer_phone"));
		info.put("shop_name", seller_shop.get("shop_name"));
		info.put("shop_avatar", UserAppInfoController.ImgPath + seller_shop.get("shop_avatar"));
		info.put("Traces", null);
		if(info.getStr("waybillnumber")!=null){
			list_traces.add(OrderTracesModel.getNewTraces(info.getStr("waybillnumber")));//平台推送查询
			info.put("Traces", list_traces);
		}
		info.put("return_id", null);
		ReturnGoodsModel rg = ReturnGoodsModel.getByG_order(info.getStr("order_sn"), 1);
		if(rg != null){
			info.put("return_id", rg.get("return_id"));
		}
		info.remove("user_id");
		info.remove("del");
		info.remove("orderids");
		info.remove("trade_num");
		info.remove("update_time");
		info.remove("phone");
		info.remove("type");
		info.remove("settlement_time");
		info.remove("country");
		info.remove("zipcode");
		info.remove("pay_time");
		info.remove("payment_channel");
		rs.put("orderdetail", info);
		this.renderJson(rs);
	}
	
	/**
	 * 确认订单接口（点击立即购买） 多个商品
	 * 购物车入口
	 * @author liushaomin
	 * 2017年7月10日
	 */
	@Clear
	public void confirmOrder(){
		Map<String, Object> rs = new HashMap<String, Object>();
		String phone = this.getPa("phone");
		String goodsids = this.getPa("goodsids");
		String sql = "SELECT seller_id,GROUP_CONCAT(id) AS goodsids FROM goods WHERE id IN("+ goodsids+") GROUP BY seller_id";
		List<Map<String, Object>> orderlist = new ArrayList<Map<String,Object>>();
		List<GoodsModel> goodslist = GoodsModel.dao.find(sql);
		for (GoodsModel item : goodslist) {
			Map<String, Object> goodsmap = new HashMap<String, Object>();
			String item_seller_id = item.getStr("seller_id");
			String item_goodsids = item.getStr("goodsids");
			List<GoodsModel> item_goodslist = GoodsModel.getGoods(item_goodsids, phone);
			goodsmap.put("goodslist", item_goodslist);
			goodsmap.put("shopname", BuyerStatisticsModel.getShop_name(item_seller_id));
			goodsmap.put("postage_type", BuyerStatisticsModel.getShopPostage_order(item_seller_id, GoodsModel.getTotal(item_goodslist)));
			goodsmap.put("number", item_goodsids.split(",").length);
			goodsmap.put("total", GoodsModel.getTotal_ContainPostage(item_goodslist, item_seller_id));
			goodsmap.put("seller_id", item.getStr("seller_id"));
			orderlist.add(goodsmap);
		}
		rs.put("defaultadress", BuyerAddressModel.getDefaultAddress(phone));
		rs.put("orderlist", orderlist);
		this.renderJson(rs);
	}
	
	/**
	 * 确认订单接口（点击立即购买） 单个商品
	 * 商品详情入口
	 * confirmOrder_single 和 confirmOrder接口返回数据结构相同 
	 * @author liushaomin
	 * 2017年7月12日
	 */
	@Clear
	public void confirmOrder_single(){
		Map<String, Object> rs = new HashMap<String, Object>();
		String phone = this.getPa("phone");
		String goodsid = this.getPa("goodsid");
		int goodsnum = this.getParaInt("goodsnum");
		String sql = "SELECT id, thumb, g_name, real_price, seller_id FROM goods WHERE id = "+ goodsid +"";
		List<GoodsModel> goodslist = GoodsModel.dao.find(sql);
		List<Map<String, Object>> orderlist = new ArrayList<Map<String,Object>>();
		for (GoodsModel item : goodslist) {
			Map<String, Object> shop_map = new HashMap<String, Object>();
			item.set("thumb", UserAppInfoController.ImgPath + item.getStr("thumb"));
			item.put("num", goodsnum);
			shop_map.put("goodslist", goodslist);
			shop_map.put("shopname", BuyerStatisticsModel.getShop_name(item.getStr("seller_id")));
			shop_map.put("postage_type", BuyerStatisticsModel.getShopPostage_order(item.getStr("seller_id"), GoodsModel.getTotal(item, goodsnum)));
			shop_map.put("total", GoodsModel.getTotal_ContainPostage(item, item.getStr("seller_id"), goodsnum));
			shop_map.put("number", 1);
			shop_map.put("seller_id", item.getStr("seller_id"));
			orderlist.add(shop_map);
		}
		rs.put("orderlist", orderlist);
		rs.put("defaultadress", BuyerAddressModel.getDefaultAddress(phone));
		this.renderJson(rs);
	}
	
	/**
	 * 提交订单接口 同时购买多种商品 一个店铺对应一个订单（暂时没有商品数量的限制）
	 * @author liushaomin
	 * 2017年7月14日
	 */
	@Clear
	public void addOrder(){
		Map<String, Object> rs = new HashMap<String, Object>();
		String phone = this.getPa("phone");
		String data = this.getPa("data");
		Map<String, Object> dataMap = Utils.toMap(data);
		UserAppModel user = UserAppModel.dao.findFirst("select * from buyer b, buyer_address ba where b.phone= '"+phone+"' and ba.id = '"+dataMap.get("buyeraddressid").toString()+"'");//获取用户收货地址
		List<Map<String,Object>> orderList = JsonUtils.toListMap(dataMap.get("orderlist"));
        List<Integer> all_goodsids = new ArrayList<Integer>();
        List<Integer> all_goodsnum = new ArrayList<Integer>();
        StringBuffer orderids_strbuf = new StringBuffer();
        boolean ischeck = true;
		for (Map<String, Object> map_orders : orderList) {//判断商品是否还有库存，没有库存的话直接返回return
			List<Map<String,Object>> goodslist = JsonUtils.toListMap(map_orders.get("goodslist"));
			for (Map<String, Object> map_goods : goodslist) {//得到所有商品的id和购买数量
				all_goodsids.add(Integer.valueOf(map_goods.get("goodsid").toString()));
				all_goodsnum.add(Integer.valueOf(map_goods.get("goodsnum").toString()));
			}
		}
		for (int i = 0; i < all_goodsids.size(); i++) {
			GoodsModel goods = GoodsModel.getGoodsStockById(all_goodsids.get(i));
			if(goods.getInt("stock") < all_goodsnum.get(i)){
				ischeck = false;
				if(!ischeck){
					rs.put("goodsname", goods.getStr("g_name"));
					rs.put("state", "isnull");
					this.renderJson(rs);
					return;
				}
			}
		}
		for (Map<String, Object> map_orders : orderList) {
			if(ischeck){//添加订单信息
				OrderInfoModel order = new OrderInfoModel();
				boolean orderboo = order.set("order_sn", Utils.getOrderSN()).set("order_status", 0).set("user_id", user.get("user_id")).set("consignee", user.get("consignee"))
						.set("phone", phone).set("country", user.get("country")).set("provice", user.get("province")).set("city", user.get("city"))
						.set("district", user.get("district")).set("address", user.get("address")).set("c_time", Utils.getDate()).set("consignee_phone", user.get("consignee_phone"))
						.set("isdelay", 0).set("buyer_message", map_orders.get("message")).set("type", 0).set("update_time", Utils.getDate()).save();
				if(orderboo){
					double order_money =0.0;//该订单总额
					double goods_money =0.0;//商品的总价
					List<Map<String,Object>> goodslist = JsonUtils.toListMap(map_orders.get("goodslist"));
					for (Map<String, Object> map_goods : goodslist) {
						int goodsid = Integer.valueOf(map_goods.get("goodsid").toString());
						int goodsnum = Integer.valueOf(map_goods.get("goodsnum").toString());
						GoodsModel goods = GoodsModel.getGoodsById(goodsid);
						new OrderGoodsModel().set("order_id", order.get("id")).set("goods_id", goodsid).set("goods_name", goods.get("g_name"))//插入OrderGoodsModel
						.set("goods_price", goods.get("real_price")).set("goods_num", goodsnum).set("goods_thumb", goods.get("thumb"))
						.set("goods_video", goods.get("videoname")).set("seller_id", goods.get("seller_id")).save();
						goods_money = Utils.add(goods_money, GoodsModel.getTotal(goods, goodsnum));//计算所有商品的总价格（不含邮费）
					    GoodsModel.dao.edit_stock_sales(goodsid, 0, goodsnum);//完成后减少库存，增加销量
						ShoppingCartModel.removeshoppingcart(phone, goodsid);//删除购物车
						rs.put("state", "suc");
					}
					order_money = Double.valueOf(GoodsModel.getTotal_ContainPostage(goods_money, map_orders.get("seller_id").toString()));
					order.set("total_price", order_money).set("postage_typeName", BuyerStatisticsModel.getShopPostage_order(map_orders.get("seller_id").toString(), goods_money)).update();
					if(orderids_strbuf.length() > 0){
						orderids_strbuf.append(",").append(order.get("id"));
					}else{
						orderids_strbuf.append(order.get("id"));
					}
				}else{
					rs.put("state", "fal");
					ischeck = false;
					return;
				}
			}
		}
		if(ischeck){
			rs.put("orderids", orderids_strbuf.toString());
		}
		this.renderJson(rs);
	}
	
	/**
	 * 取消订单--可批量
	 * 状态改为6，归还库存,减少销量 TODO 考虑取消订单是否直接删除订单
	 * @author lifuqiang
	 * 2016-10-20
	 */
	@Clear
	public void cancelOrder(){
		String order_ids = this.getPa("order_ids");
		String[] orderids  = order_ids.trim().split(",");
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		boolean result = false;
		for (String item : orderids) {
			OrderInfoModel order = OrderInfoModel.dao.findById(item);
			if(order != null){
				List<OrderGoodsModel> ordergoods = OrderGoodsModel.getByOrderId(order.getInt("id"));
				boolean boo = order.set("order_status", 6).set("update_time", Utils.getDate()).update();
				if(boo){
					for (OrderGoodsModel ordergoods_item : ordergoods) {
						GoodsModel.dao.edit_stock_sales(ordergoods_item.getInt("goods_id"), 1, ordergoods_item.getInt("goods_num"));//完成后归还库存，减少销量
					}
					result = true;
				}
			}
		}
		if(result){
			rs.put("state", "suc");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 删除订单
	 * 改del为1
	 * @author liushaomin
	 * 2017年4月18日
	 */
	@Clear
	public void delOrder(){
		String ordersn = this.getPara("order_sn");
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		OrderInfoModel orderinfo = OrderInfoModel.getOrderBySN(ordersn);
		boolean boo = orderinfo.set("del", 1).update();
		if(boo){
			List<ReturnGoodsModel> return_g = ReturnGoodsModel.getByG_order(ordersn);
			for (ReturnGoodsModel item : return_g) {
				item.set("del", 1).update();
			}
			rs.put("state", "suc");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 发货提醒
	 * @author lifuqiang
	 * 2017-4-11
	 */
	@Clear
	public void remindShipment(){
		String order_sn = getPa("order_sn");
		String phone = getPa("phone");
		UserAppModel user = UserAppModel.getByPhone(phone);
		String seller_phone = OrderInfoModel.getSellerByOrdersn(order_sn);
		OrderInfoModel info = OrderInfoModel.getOrderBySN(order_sn);
		Map<String, Object> rs = new HashMap<String, Object>();
		int isRemindShipment = info.getInt("isRemindShipment");
		if(isRemindShipment == 0){
			String content = "买家 " + user.getStr("nick") + ",提醒您 赶紧去发货！";
			PushUtils.MSG_Single(seller_phone, "B01", content);
			if(info.set("isRemindShipment", 1).update()){
				rs.put("state", "suc");
			}else{
				rs.put("state", "fal");
			}
		}else{
			rs.put("state", "exit");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 卖家发货
	 * 状态修改为3 已发货
	 * @author lifuqiang
	 * 2017-3-24
	 */
	@Clear
	public void dealOrder(){
		String order_sn = getPa("order_sn");
		String waybillnumber = getPa("waybillnumber");
		String express = getPa("express");
		OrderInfoModel orderinfo = OrderInfoModel.getOrderBySN(order_sn);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		boolean boo = orderinfo.set("waybillnumber", waybillnumber).set("express", express).set("order_status", 3).set("update_time", Utils.getDate())
					.set("bill_time", Utils.getDate()).update();
		if(boo){
			rs.put("state", "suc");
			new OrderTracesModel().set("waybillnumber", waybillnumber).set("update_time", Utils.getDate()).save();//订单轨迹添加新订单轨迹
			if(log.isInfoEnabled()){log.info(KDNiaoUtils.orderTracesSubByJson(express, waybillnumber));}//快递鸟订阅此订单
			PushUtils.MSG_Single(orderinfo.getStr("phone"), "A03", "您买的宝贝:已经发货啦！！");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 卖家修改订单价格
	 * @author liushaomin
	 * 2017年8月2日
	 */
	@Clear
	public void modify_OrderPrice(){
		String order_sn = getPa("order_sn");
		String price = getPa("price");
		OrderInfoModel orderinfo = OrderInfoModel.getOrderBySN(order_sn);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		boolean boo = orderinfo.set("total_price", price).set("update_time", Utils.getDate()).update();
		if(boo){
			rs.put("state", "suc");
			PushUtils.MSG_Single(orderinfo.getStr("phone"), "A01", "您的订单价格已修改，请查看！！");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 延长收货（更改是否延期）state = 1
	 * 买家确认收货（订单状态改为待评价5）state = 2
	 * @author lifuqiang
	 * 2016-11-16
	 */
	@Clear
	public void delayOrder(){
		String order_sn = getPa("order_sn");
		int state = getParaInt("state");
		OrderInfoModel orderinfo = OrderInfoModel.getOrderBySN(order_sn);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		if(state == 1){//延长收货
			boolean boo = orderinfo.set("isdelay", 1).set("update_time", Utils.getDate()).update();
			if(boo){
				rs.put("state", "suc");
			}
		}else{//买家确定收货
			boolean boo = orderinfo.set("order_status", 5).set("update_time", Utils.getDate()).update();
			if(boo){
				BuyerStatisticsModel.Update_Add_Usable(orderinfo);
				rs.put("state", "suc");
			}
		}
		this.renderJson(rs);
	}
	
	/**
	 * 评价商品
	 * 订单状态改为7订单已完成
	 * @author lifuqiang
	 * 2016-11-7
	 */
	@Clear
	public void goodsEvaluation(){
		UploadFile thumb1 = getfile("thumb1");
		UploadFile thumb2 = getfile("thumb2");
		UploadFile thumb3 = getfile("thumb3");
		UploadFile thumb4 = getfile("thumb4");
		int orderid = getParaInt("orderid");
		int anonymous = getParaInt("anonymous");//1为匿名
		String evaluation = getPa("evaluation");
		int servicelevel = getParaInt("servicelevel");//服务态度
		int logisticlevel = getParaInt("logisticlevel");//物流
		int goodslevel = getParaInt("goodslevel");//商品描述
		OrderInfoModel orderinfo = OrderInfoModel.dao.findById(orderid);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		int userid = orderinfo.get("user_id");
		if( 1 == anonymous){
			userid = -1;
		}
		List<OrderGoodsModel> ordergoods = OrderGoodsModel.getByOrderId(orderid);
		boolean boo = true;
		for (OrderGoodsModel ordergoods_item : ordergoods) {
			EvaluationModel evaluationmodel = new EvaluationModel();
			if(boo){//批量添加评论，获取评论时根据orderid去重
				boo = evaluationmodel.set("user_id", userid).set("order_id", orderid).set("evaluation", Utils.clearXSS(evaluation)).set("gid", ordergoods_item.get("goods_id"))
					.set("thumb1", Utils.getThumbName(thumb1)).set("thumb2", Utils.getThumbName(thumb2)).set("thumb3", Utils.getThumbName(thumb3))
					.set("thumb4", Utils.getThumbName(thumb4)).set("service_level", servicelevel).set("logistic_level", logisticlevel)
					.set("goods_level", goodslevel).set("seller_id", ordergoods_item.get("seller_id")).set("c_time", Utils.getDate()).save();
			}
		}
		if(boo){
			orderinfo.set("order_status", 7).set("finish_time", Utils.getDate()).set("update_time", Utils.getDate()).update();
			BuyerStatisticsModel.UpdateSeller_credit(ordergoods.get(0).getInt("seller_id").toString());//买家提交评论后  更新商家信誉度
			rs.put("state", "suc");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 判断是否重复提交 退款申请
	 * @author liushaomin
	 * 2017年4月18日
	 */
	@Clear
	public void refundApply_repeat(){
		String order_sn = getPa("order_sn");
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "suc");
		if(ReturnGoodsModel.isReturnByOrdersn(order_sn)){
			rs.put("state", "fal");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 买家提交退款申请 
	 * 提交申请后订单状态改成（8）退款中，退款状态改为（0）提交退款申请
	 * @author liushaomin
	 * 2016年11月16日
	 */
	@Clear
	public void refundApply(){
		String order_sn = getPa("order_sn");
		String returnreason = getPa("returnreason");
		OrderInfoModel order = OrderInfoModel.getOrderBySN(order_sn);
		UserAppModel user = UserAppModel.getByPhone(order.getStr("phone")); 
		List<OrderGoodsModel> goods = OrderGoodsModel.getByOrderId(order.getInt("id"));
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		ReturnGoodsModel returngoods = new ReturnGoodsModel();
		String data = ReturnGoodsModel.getData(returngoods, 0, "买家", "提交了退款申请，等待商家处理。");
		boolean boo = returngoods.set("buy_id", user.get("user_id")).set("phone", order.getStr("phone")).set("seller_id", goods.get(0).get("seller_id"))
		.set("g_order", order_sn).set("return_money", order.get("total_price")).set("return_reason", returnreason).set("return_status", 0).set("isreturn_goods", 0)
		.set("data", data).set("c_time", Utils.getDate()).set("update_time", Utils.getDate()).save();
		if(boo){
			new OrderInfoModel().findById(order.getInt("id")).set("order_status", 8).update();
			PushUtils.MSG_Single(OrderInfoModel.getSellerByOrdersn(order_sn), "B04", "您有订单的退款申请，请及时处理...");
			rs.put("state", "suc");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 买家撤销退款申请
	 * 设置退货状态为（3）撤销退款申请，订单状态改为（2）待发货；
	 * @author lifuqiang
	 * 2016-11-24
	 */
	@Clear
	public void buyerRevokeRefund(){
		String ordercode = getPa("ordercode");
		ReturnGoodsModel returngoods = ReturnGoodsModel.getByG_order(ordercode, 0);
		OrderInfoModel order = OrderInfoModel.getOrderBySN(ordercode);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		boolean boo_return = returngoods.set("return_status", 3).set("update_time", Utils.getDate()).set("data", ReturnGoodsModel.getData(returngoods, 1, "买家", "商家已撤销退款申请")).update();
		boolean boo_info = order.set("order_status", 2).set("update_time", Utils.getDate()).update();
		if(boo_return && boo_info){
			PushUtils.MSG_Single(OrderInfoModel.getSellerByOrdersn(ordercode), "B04", "您有新的订单状态通知，去看看吧！");
			rs.put("state", "suc");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 商家同意退款申请，等待平台退款，归还库存，设置退货状态为1；
	 * 付款完成后，订单状态改为9退款成功，退货状态改为8退款完成
	 * @author lifuqiang
	 * 2016-11-24
	 * @throws Exception 
	 */
	@Clear
	public void sellerAgreeRefund(){
		String ordercode = getPa("ordercode");
		ReturnGoodsModel returngoods = ReturnGoodsModel.getByG_order(ordercode, 2);
		OrderInfoModel order = OrderInfoModel.getOrderBySN(ordercode);
		String pay_channel = "";
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		if(order.getInt("order_status") == 9){
			rs.put("state", "repeat");	
		}else{
			boolean upboo = OrderInfoModel.UpdateOrderStatus(order, 9);
			boolean boo_refund = false; 
			if(upboo){
				OrderInfoModel order_all = OrderInfoModel.isTotalOrder(order.get("id"));
				if(order_all != null){//多个订单支付情况
					if("0".equals(order_all.getStr("payment_channel"))){//支付宝退款
						boo_refund = AlipayUtils.refund(order_all.getStr("order_sn"), order.get("total_price"));
						pay_channel = "alipay";
					}else if("1".equals(order_all.getStr("payment_channel"))){//微信退款
						boo_refund = WeixinUtils.refund(order_all.getStr("order_sn"), order_all.getFloat("total_price"), order.getFloat("total_price"));
						pay_channel = "weixin";
					}
				}else{//单个订单支付情况
					if("0".equals(order.get("payment_channel"))){//支付宝退款
						boo_refund = AlipayUtils.refund(order.getStr("order_sn"), order.get("total_price"));
						pay_channel = "alipay";
					}else if("1".equals(order.get("payment_channel"))){//微信退款
						boo_refund = WeixinUtils.refund(order.getStr("order_sn"), order.getFloat("total_price"), order.getFloat("total_price"));
						pay_channel = "weixin";
					}
				}
			}
			if(boo_refund){
				returngoods.set("return_status", 1).set("update_time", Utils.getDate()).set("data", ReturnGoodsModel.getData(returngoods, 1, "商家", "商家已同意退款")).update();
				returngoods.set("return_status", 8).set("update_time", Utils.getDate()).set("data", ReturnGoodsModel.getData(returngoods, -1, "热播购系统", "已退款成功")).update();
				PaymentModel payment =  PaymentModel.getPaymentByOrderSN_Channel_state(order.getStr("order_sn"), pay_channel, 2);
				payment.set("back_time", Utils.getDate()).set("state", 3).update();	
				BuyerStatisticsModel.Update_Reduce_Disable(order);
				List<OrderGoodsModel> og = OrderGoodsModel.getByOrderId(order.getInt("id"));
				for (OrderGoodsModel item : og) {
					GoodsModel.dao.edit_stock_sales(item.getInt("goods_id"), 1, item.getInt("goods_num"));
				}
				PushUtils.MSG_Single(order.getStr("phone"), "A05", "您的退款进度更新啦！去看看吧！");
				rs.put("state", "suc");
			}else{
				OrderInfoModel.UpdateOrderStatus(order, 8);
			}
		}
		this.renderJson(rs);
	}
	
	/**
	 * 提交退货申请
	 * @author lifuqiang
	 * 2017-4-17
	 */
	@Clear
	public void returnApply(){
		UploadFile thumb1 = getfile("thumb1");
		UploadFile thumb2 = getfile("thumb2");
		UploadFile thumb3 = getfile("thumb3");
		String ordercode = this.getPa("ordercode");
		String phone = this.getPa("phone");
		String returnreason = this.getPa("returnreason");
		UserAppModel user = UserAppModel.getByPhone(phone); 
		OrderInfoModel order = OrderInfoModel.getOrderBySN(ordercode);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		ReturnGoodsModel o_returngoods = ReturnGoodsModel.getByG_order(ordercode, 1);
		if(o_returngoods != null){
			o_returngoods.delete();
		}
		ReturnGoodsModel returngoods = new ReturnGoodsModel();
		String data = ReturnGoodsModel.getData(returngoods, 0, "买家", "买家提交了退货申请");
		boolean boo = returngoods.set("buy_id", user.get("user_id")).set("phone", phone).set("seller_id", OrderInfoModel.getOrderSeller_id(ordercode))
				.set("g_order", ordercode).set("return_money", order.get("total_price")).set("return_reason", returnreason).set("return_status", 0).set("thumb1", Utils.getThumbName(thumb1))
				.set("thumb2", Utils.getThumbName(thumb2)).set("thumb3", Utils.getThumbName(thumb3)).set("isreturn_goods", 1).set("data", data).set("c_time", Utils.getDate())
				.set("update_time", Utils.getDate()).save();
		if(boo){
			returngoods.set("data", ReturnGoodsModel.getData(returngoods, -1, "热播购系统", "等待商家处理")).update();
			new OrderInfoModel().findById(order.getInt("id")).set("order_status", 10).update();
			PushUtils.MSG_Single(OrderInfoModel.getSellerByOrdersn(ordercode), "B04", "您有订单的退货申请，请及时处理...");
			rs.put("state", "suc");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 买家退货提交物流信息
	 * @author lifuqiang
	 * 2017-4-17
	 */
	@Clear
	public void buyerShipment(){
		int returnid = this.getParaToInt("returnid");
		String express = this.getPa("express");
		String waybillnumber = this.getPa("waybillnumber");
		ReturnGoodsModel returngoods = ReturnGoodsModel.dao.findById(returnid);
		OrderTracesModel traces = new OrderTracesModel();
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		boolean boo = returngoods.set("express", express).set("waybillnumber", waybillnumber).set("return_status", 4).set("update_time", Utils.getDate())
					.set("data", ReturnGoodsModel.getData(returngoods, 4, "买家", "创建物流信息")).update();
		if(boo){
			returngoods.set("data", ReturnGoodsModel.getData(returngoods, -4, "热播购系统", "等待商家收货")).update();
			traces.set("waybillnumber", waybillnumber).set("update_time", Utils.getDate()).save();
			if(log.isInfoEnabled()){log.info(KDNiaoUtils.orderTracesSubByJson(express, waybillnumber));}//快递鸟订阅此订单
			UserAppModel us = UserAppModel.dao.findById(returngoods.get("seller_id"));
			PushUtils.MSG_Single(us.getStr("phone"), "B04", "您有新的订单状态通知，去看看吧！");
			rs.put("state", "suc");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 提供物流公司编码对照
	 * @author lifuqiang
	 * 2017-4-17
	 */
	@Clear
	public void giveExpress(){
		String sql = "select * from express ";
		List<ExpressModel> express = ExpressModel.dao.find(sql);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("express", express);
		this.renderJson(rs);
	}
	
	/**
	 * 单号识别，暂时没有用
	 * @author lifuqiang
	 * 2017-4-17
	 */
	@Clear
	public void numberRecognition() {
		String waybillnumber = this.getPa("waybillnumber");
		String json = KDNiaoUtils.numberRecognition(waybillnumber);
		List<Map<String, Object>> list = JsonUtils.jsonKDNiao(json);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("data", list);
		this.renderJson(rs);
	}
	
	/**
	 * 即时查询物流信息
	 * @author lifuqiang
	 * 2017-4-17
	 */
	@Clear
	public void getOrderInstantJson() {
		String waybillnumber = this.getPa("waybillnumber");
		String express = this.getPa("express");//必须是物流公司编码，如：韵达传过来是：YD
		String json = KDNiaoUtils.getOrderJson(express, waybillnumber);
		List<Map<String, Object>> list = JsonUtils.jsonKDNiao(json);
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("data", list);
		this.renderJson(rs);
	}
	
	/**
	 * 得到推送的物流信息
	 * @author lifuqiang
	 * 2017-4-17
	 */
	@SuppressWarnings("unchecked")
	@Clear 
	public void getOrderPushJson(){
		Map<String, Object> rs = new HashMap<String, Object>();
		String waybillnumber = this.getPa("waybillnumber");
		String sql = "select * from order_traces where waybillnumber = '"+waybillnumber+"'";
		OrderTracesModel traces = OrderTracesModel.dao.findFirst(sql);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		boolean boo = false;
		if(traces!=null){
			String data = traces.get("data");
			if(data==null){
				List<Map<String, Object>> list_data = new ArrayList<Map<String, Object>>(); 
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("AcceptStation", "该包裹正在被揽件！");
				map.put("AcceptTime", Utils.getDate());
				list_data.add(map);
				rs.put("data", list_data);
				rs.put("Success", boo);
			}else{
				List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>(); 
				Map<String, Object> map_date = new HashMap<String, Object>();
				list.add(JsonUtils.deserialize(data));
				for(Map<String, Object> map : list){	//重取排序
					List<Map<String, Object>> list3 = (List<Map<String, Object>>) map.get("Traces");
					if(list3.size() != 0){
						for (int i = list3.size()-1; i >=0 ; i--) {
							map_date = (Map<String, Object>)list3.get(i);
							list2.add(map_date);
							map.put("Traces", list2);
						}
					}else{
						map_date.put("AcceptStation", "该包裹暂无物流信息！");
						map_date.put("AcceptTime", Utils.getDate());
						list2.add(map_date);
						map.put("Traces", list2);
					}
				}
				rs.put("data", list);
				rs.put("Success", true);
			}
		}else{
			rs.put("Success", boo);
			rs.put("data", "该订单不存在！");
		}
		this.renderJson(rs);
	}
	
	/**
	 * 退货
	 * 退货是买家填写退货物流信息
	 * @author liushaomin
	 * 2017年4月25日
	 */
	@Clear
	public void returnGoodsLogistics(){
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("state", "fal");
		String id = this.getPa("id");
		String waybillnumber = this.getPa("waybillnumber");
		String 	express = this.getPa("express");
		ReturnGoodsModel reModel = ReturnGoodsModel.dao.findById(id);
		if(reModel.set("return_status", 4).set("express", express).set("waybillnumber", waybillnumber).set("update_time", Utils.getDate()).set("data", ReturnGoodsModel.getData(reModel, 4, "买家", "买家创建了物流信息")).update()){
			reModel.set("data", ReturnGoodsModel.getData(reModel, -4, "热播购系统", "等待商家收货")).update();
			rs.put("state", "suc");
		}
		this.renderJson(rs);
	}
}
